package com.zygh.policeasset.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.fastjson.JSONObject;
import com.zygh.policeasset.component.CommonResult;
import com.zygh.policeasset.listenter.QrCodeInfoListener;
import com.zygh.policeasset.mapper.QrCodeInfoMapper;
import com.zygh.policeasset.pojo.QrCodeGenerated;
import com.zygh.policeasset.pojo.QrCodeInfo;
import com.zygh.policeasset.pojo.dto.QrCodeDistributionDTO;
import com.zygh.policeasset.pojo.imports.QrCodeInfoImport;
import com.zygh.policeasset.service.DailyProjectService;
import com.zygh.policeasset.service.PurchaseService;
import com.zygh.policeasset.service.QrCodeGeneratedService;
import com.zygh.policeasset.service.SettlementService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RequestMapping({"/qrCodeGenerated"})
@Api(tags = {"铝制标牌分配"})
@RestController
public class QrCodeGeneratedController {
    @Autowired
    SettlementService settlementService;
    @Autowired
    PurchaseService purchaseService;
    @Autowired
    DailyProjectService dailyProjectService;
    @Autowired
    QrCodeGeneratedService qrCodeGeneratedService;
    @Autowired
    QrCodeInfoMapper qrCodeInfoMapper;

    @RequestMapping(value = {"/add"}, method = {RequestMethod.POST})
    @ApiOperation("添加")
    public Object add(@RequestBody QrCodeGenerated qrCodeGenerated) {
        if (this.qrCodeGeneratedService.selectCount(qrCodeGenerated.getType(), qrCodeGenerated.getBuildNum(), qrCodeGenerated.getSectionId()).intValue() > 0) {
            return new CommonResult().validateFailed("该项目已领取过标牌,无需重复添加");
        }
        if (this.qrCodeGeneratedService.add(qrCodeGenerated).intValue() > 0) {
            return new CommonResult().success();
        }
        return new CommonResult().validateFailed("操作失败");
    }

    @RequestMapping(value = {"/findAll"}, method = {RequestMethod.GET})
    @ApiOperation("查询所有")
    public Object findAll(int pageNum, int pageSize,
                          @RequestParam(value = "type", required = false) String type,
                          @RequestParam(value = "name", required = false) String name,
                          @RequestParam(value = "buildNum", required = false) String buildNum,
                          @RequestParam(value = "sectionId", required = false) Integer sectionId,
                          @RequestParam(value = "qrCode", required = false) String qrCode,
                          @RequestParam(value = "status", required = false) Integer status,
                          @RequestHeader("findAll") boolean findAll,
                          @RequestHeader("unitId") Integer unitId,
                          @RequestHeader(value = "userId", required = false) Integer userId) {
        if (findAll) {
            return this.qrCodeGeneratedService.selectList(pageNum, pageSize, type, name, buildNum, sectionId, null, qrCode, null, status);
        }
        return this.qrCodeGeneratedService.selectList(pageNum, pageSize, type, name, buildNum, sectionId, unitId, qrCode, userId, status);
    }

    @RequestMapping(value = {"/selectById"}, method = {RequestMethod.GET})
    @ApiOperation("通过id查询")
    public Object selectById(@RequestParam(value = "id", required = false) Integer id) {
        return this.qrCodeGeneratedService.selectById(id);
    }

    @RequestMapping(value = {"/selectProject"}, method = {RequestMethod.GET})
    @ApiOperation("项目查询")
    public Object selectProject(@RequestParam(value = "type", required = false) String type, @RequestParam(value = "name", required = false) String name, @RequestParam(value = "buildNum", required = false) String buildNum, @RequestParam(value = "sectionId", required = false) Integer sectionId, @RequestHeader("findAll") boolean findAll, @RequestHeader("unitId") Integer unitId) {
        if (findAll) {
            return this.qrCodeGeneratedService.selectProject(type, name, buildNum, sectionId, null);
        }
        return this.qrCodeGeneratedService.selectProject(type, name, buildNum, sectionId, unitId);
    }

    @RequestMapping(value = {"/exportQrCode"}, method = {RequestMethod.GET})
    @ApiOperation("资产二维码信息导出")
    public Object exportQrCode(@RequestParam("id") Integer id, HttpServletResponse response) {
        return this.qrCodeGeneratedService.selectQrCode(id, response);
    }

    @RequestMapping(value = {"/selectListByQrCodeGeneratedId"}, method = {RequestMethod.GET})
    @ApiOperation("查询二维码详细信息")
    public Object selectListByQrCodeGeneratedId(int pageNum, int pageSize, @RequestParam("qrCodeGeneratedId") Integer qrCodeGeneratedId) {
        return this.qrCodeGeneratedService.selectListByQrCodeGeneratedId(pageNum, pageSize, qrCodeGeneratedId);
    }

    @RequestMapping(value = {"/QrCodeDistribution"}, method = {RequestMethod.POST})
    @ApiOperation("二维码分配")
    public Object QrCodeDistribution(@RequestBody QrCodeDistributionDTO qrCodeDistribution) {
        if (this.qrCodeGeneratedService.qrCodeDistribution(qrCodeDistribution).intValue() > 0) {
            return new CommonResult().success();
        }
        return new CommonResult().validateFailed("操作失败");
    }

    @RequestMapping(value = {"/updateQrCodeGeneratedIdIsNull"}, method = {RequestMethod.POST})
    @ApiOperation("二维码解除分配")
    public Object updateQrCodeGeneratedIdIsNull(@RequestBody QrCodeDistributionDTO qrCodeDistribution) {
        if (this.qrCodeGeneratedService.updateQrCodeGeneratedIdIsNull(qrCodeDistribution).intValue() > 0) {
            return new CommonResult().success();
        }
        return new CommonResult().validateFailed("操作失败");
    }

    @RequestMapping(value = {"/undistributedQrCode"}, method = {RequestMethod.GET})
    @ApiOperation("查询未分配铝制二维码")
    public Object undistributedQrCode(@RequestParam(value = "counter", required = false) Integer counter, @RequestParam(value = "qrCode", required = false) String qrCode) {
        if (this.qrCodeGeneratedService.undistributedSelect().intValue() < counter.intValue()) {
            return new CommonResult().validateFailed("库存不足");
        }
        List<QrCodeInfo> list = this.qrCodeGeneratedService.undistributedQrCode(counter, qrCode);
        Map map = new HashMap(16);
        map.put(NormalExcelConstants.DATA_LIST, list);
        map.put("num", Integer.valueOf(list.size()));
        return new CommonResult().success(map);
    }

    @RequestMapping(value = {"/findPrintQrCode"}, method = {RequestMethod.GET})
    @ApiOperation("项目打印二维码查询")
    public Object findPrintQrCode(@RequestParam(value = "qrCodeGeneratedId", required = false) Integer qrCodeGeneratedId, @RequestParam(value = "type", required = false) Integer type) {
        return this.qrCodeGeneratedService.findPrintQrCode(qrCodeGeneratedId, type);
    }

    @RequestMapping(value = {"/printQrCodeImport"}, method = {RequestMethod.POST})
    @ApiOperation("项目打印二维码资产信息导入")
    public Object printQrCodeImport(@RequestBody MultipartFile file, @RequestParam("qrCodeGeneratedId") Integer qrCodeGeneratedId) throws IOException {
        try {
            EasyExcel.read(file.getInputStream(), QrCodeInfoImport.class, new QrCodeInfoListener(qrCodeGeneratedId)).sheet().doRead();
            return new CommonResult().success();
        } catch (ExcelAnalysisException e) {
            e.printStackTrace();
            return new CommonResult().validateFailed(e.getCause().getMessage());
        } catch (ConstraintViolationException e2) {
            e2.printStackTrace();
            return new CommonResult().validateFailed(e2.getMessage());
        }
    }

    @RequestMapping(value = {"/printQrCodeExport"}, method = {RequestMethod.GET})
    @ApiOperation("项目打印二维码信息导出")
    public Object printQrCodeExport(@RequestParam("qrCodeGeneratedId") Integer qrCodeGeneratedId, HttpServletResponse response) {
        return this.qrCodeGeneratedService.selectQrCodePrintQrCode(qrCodeGeneratedId, response);
    }

    @RequestMapping(value = {"/printQrCodeDelete"}, method = {RequestMethod.POST})
    @ApiOperation("项目打印二维码信息删除")
    public Object printQrCodeDelete(@RequestBody JSONObject json) {
        if (this.qrCodeGeneratedService.printQrCodeDelete(json.getString("ids")).intValue() > 0) {
            return new CommonResult().success();
        }
        return new CommonResult().validateFailed("操作失败");
    }

    @DeleteMapping({"/delete/{id}"})
    @ApiOperation("二维码删除")
    public Object delete(@PathVariable Integer id) {
        if (this.qrCodeInfoMapper.findPrintQrCode(id, null).size() > 0) {
            return new CommonResult().validateFailed("请先删除项目中的铝制或内场二维码");
        }
        if (this.qrCodeGeneratedService.deleteByQrCodeGeneratedId(id) > 0) {
            return new CommonResult().success();
        }
        return new CommonResult().validateFailed("删除失败");
    }
}